#include <etcd/Client.hpp>
#include <etcd/KeepAlive.hpp>
#include <etcd/Response.hpp>
#include <etcd/Watcher.hpp>
#include <etcd/Value.hpp>
#include <thread>

void Callback(const etcd::Response resp)
{
    if(resp.is_ok() == false)
    {
        std::cout << "watch failed" << resp.error_message() << std::endl;
        return;
    }
    for(auto const& ev: resp.events())
    {
        if(ev.event_type() == etcd::Event::EventType::PUT)
        {
            std::cout << "service changed" << std::endl;
            std::cout << "current kv is: " << ev.kv().key() << "-" << ev.kv().as_string() << std::endl;
            std::cout << "previous kv is: " << ev.prev_kv().key() << "-" << ev.prev_kv().as_string() << std::endl;
        }
        else if(ev.event_type() == etcd::Event::EventType::DELETE_)
        {
            std::cout << "service deleted" << std::endl;
            std::cout << "previous kv is: " << ev.prev_kv().key() << "-" << ev.prev_kv().as_string() << std::endl;
        }
    }
}

int main(int argc, char* argv[])
{
    std::string etcd_host = "http://127.0.0.1:2379";
    // 1.创建etcd客户端
    etcd::Client client(etcd_host);

    // 2.获取指定的键值对信息
    auto resp = client.ls("/service/user").get();
    if(resp.is_ok() == false)
    {
        std::cout << "get failed" << resp.error_message() << std::endl;
        return -1;
    }

    // 3.遍历键值对信息
    int sz = resp.keys().size();
    for(int i = 0; i < sz; ++i)
    {
        std::cout << resp.value(i).as_string() << " could provide[" << resp.key(i) << "]service" << std::endl; 
    }

    // 4.实例化一个键值对监控对象
    auto watcher = etcd::Watcher(client, "/service", Callback, true);
    watcher.Wait();

    return 0;
}